/**
 * Java Enterprise in a Nutshell, Third Edition, 
 * by Jim Farley and William Crawford 
 * with Prakash Malani, John G. Norman, and Justin Gehtland. 
 * Copyright 2006 O'Reilly Media, Inc., 0-596-10142-2.
 *  
 * Reworked by Vladimir Tarasov, 2009-08-26.
 * Tested with JDK 1.6.
 * 
 * Before running this client, start AccountManagerServer and 
 * run AccountManagerClient_Manage first,
 * then press Shift+F6 to run AccountManagerClient_Search.
 * 
 * If you want to run the example locally, change the host name below.
 */
package tavl_rmi.factory;

import java.net.MalformedURLException;
import java.rmi.Naming;
import tavl_rmi.accountmanager.AccountManager;
import tavl_rmi.account.Account;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

/**
 * An example client for an RMI-exported AccountManager. 
 * It is used to look up existing account objects.
 * Note, that retrieved account objects are themselves RMI-exported.
 */
public class AccountManagerClient_Search {

    /**
     * reference to the proxy for the remote object
     */
    private AccountManager mgr;

    public static void main(String argv[]) {
        AccountManagerClient_Search client = new AccountManagerClient_Search();
        client.testAccountManager("Fred");
        client.testAccountManager("Bill");
    }

    public AccountManagerClient_Search() {
        // rmiregistry on the lab server listens to port 1099
        final String host = "rmi://devdisapp.dyndns.org:1099/";
        try {
            // Lookup remote account manager object
            mgr = (AccountManager) Naming.lookup(host + "acctManager");
        } catch (RemoteException re) {
            System.err.println("Remote exception while looking up account: " +
                    re.getMessage());
        } catch (NotBoundException nbe) {
            System.err.println("Server object not found at expected URL: " +
                    nbe.getMessage());
        } catch (MalformedURLException mue) {
            System.err.println("Bad RMI URL given for server object: " +
                    mue.getMessage());
        }
    }

    private void testAccountManager(String name) {
        try {
            Account acct = mgr.getAccount(name);
            if (acct != null) {
                System.out.println("Got account, name = " + acct.getName());
                acct.deposit(1000);
                System.out.println("New account balance = " + acct.getBalance());
            } else {
                System.out.println("Account " + name + " not found");
            }
        } catch (RemoteException re) {
            System.err.println("Remote exception while testing accounts: " +
                    re.getMessage());
        }
    }
}